package parroty;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import services.OAuthRobotPAService;
import services.ParrotyService;
import services.TagParticipantService;
import tags.Tag;

import com.google.gdata.util.ServiceException;
import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Annotation;
import com.google.wave.api.Blip;
import com.google.wave.api.ElementType;
import com.google.wave.api.Event;
import com.google.wave.api.EventType;
import com.google.wave.api.FormElement;
import com.google.wave.api.Gadget;
import com.google.wave.api.GadgetView;
import com.google.wave.api.Range;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;
import com.google.wave.api.oauth.impl.PopupLoginFormHandler;

import datastore.LogOfTag;
import datastore.PMF;

public class ParrotyServlet extends AbstractRobotServlet {
    
 private final static String ADDPARTICIPANT = "http://gadgets-pa.googlecode.com/svn/trunk/%20gadgets-pa/AJAX/addParticipant.xml";
 
 private TagParticipantService tagParticipantService = new TagParticipantService(); 
 private ParrotyService parrotyService = new ParrotyService(tagParticipantService);
  
 
  // main method for response on user event	 
  @Override
  public void processEvents(RobotMessageBundle bundle) {
    Wavelet wavelet = bundle.getWavelet();
    
    // robot added self
    if (bundle.wasSelfAdded()) {    	    	
    	parrotyService.addParticipant(wavelet.getRootBlip().getDocument());    	
    }
    
    
    for (Event e: bundle.getEvents()) {
    	
    	if (e.getType() == EventType.FORM_BUTTON_CLICKED){
    		

    		Gadget gadget = parrotyService.getGadgetByUrl(e.getBlip(), ADDPARTICIPANT);
    		if(gadget != null){
    			parrotyService.addParticipantToWavelet(gadget, wavelet, gadget.getField(e.getModifiedBy()), e.getModifiedBy());
    		}
    		
	    }
	    
	    if (e.getType() == EventType.DOCUMENT_CHANGED){	    	
	    	
	    	
	    	String modifiedBy = e.getModifiedBy();
	    	Blip blip = e.getBlip();
	    	TextView textView = blip.getDocument();
	    	
	    	
	    	parrotyService.isAlertGadgetInBlipThanDeleteIt(blip, textView); 
	    	
	    	
	    	parrotyService.setMessagesFromGadgetToBlip(blip, textView, modifiedBy);
	    	parrotyService.setTagToWaveletDataDocument(wavelet, blip, modifiedBy);
	    	
	    }
	    
	    // add to blip gadget with tags
	    if (e.getType() == EventType.BLIP_SUBMITTED){	    	
	    	if(!e.getBlip().getBlipId().equals(wavelet.getRootBlipId())){
	    		parrotyService.insertTagGadget(e.getBlip(),wavelet,e.getModifiedBy());
	    	}
	    }
	   
	}
  }
}